#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"
#include <pthread.h>

#define CONV(name) ((struct sockaddr *)(name))
using namespace LogModule;
int sockfd;

void *handle_read(void *arg)
{
    while (true)
    {
        char buffer[1024];
        int n = ::read(sockfd, buffer, sizeof(buffer) - 1);
        if (n == -1)
        {
            LOG(LogLevel::ERROR) << "read failed";
            continue;
        }
        buffer[n] = 0;
        std::cout << buffer << std::endl;
    }
}

int main()
{

    std::string ip = "47.98.139.142";
    uint16_t port = 8080;

    sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "create socket failed";
        return 2;
    }
    LOG(LogLevel::INFOMATION) << "create socket success";

    struct sockaddr_in inet;
    inet.sin_family = AF_INET;
    inet.sin_addr.s_addr = ::inet_addr(ip.c_str());
    inet.sin_port = ::htons(port);

    // 连接
    int n = ::connect(sockfd, CONV(&inet), sizeof(inet));
    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "connect failed";
        return 3;
    }

    LOG(LogLevel::INFOMATION) << "connect  success";

    // 认证信息
    ::write(sockfd, "qt", 2);

    // 多线程读取
    pthread_t thread_id;
    int ret = pthread_create(&thread_id, NULL, handle_read, NULL);

    std::string message;
    while (true)
    {
        std::cout << "Please enter#";
        getline(std::cin, message);

        if (message.size() == 0)
        {
            continue;
        }
        int n = ::write(sockfd, message.c_str(), message.size());
        if (n == -1)
        {
            LOG(LogLevel::ERROR) << "write failed";
            continue;
        }
    }

    ::close(sockfd);
    return 0;
}